/**
 * Created by DELL on 2017/6/7.
 */

import React  from 'react';
import {

    StyleSheet,
    Text,
    View,
    TextInput,
    Image,
    PixelRatio,
    TouchableHighlight,
    TouchableOpacity,
    Modal,
    ListView,
    TouchableWithoutFeedback,
    Button,

} from 'react-native';

import ImagePicker from 'react-native-image-picker' ;
var Platform = require('Platform');

import BaseComponent, {base, AppIndictor} from '../../base/Base' ;

var url_head = require('../../imgs/mine/head.png');//默认头像地址
var url = require('../../imgs/mine/back.png');

let {
    N005_USERS$_EDIT_SYSUSERS,// 修改用户信息
    N007_USERS$_AVART,//  上传头像
} = base.requests;


let {
    USER_INFO,
} = base.fields;

var options = { // 弹出框配置
    title:'请选择',
    cancelButtonTitle:'取消',
    takePhotoButtonTitle:'拍照',
    chooseFromLibraryButtonTitle:'选择相册',
    cameraType: 'back',
    mediaType: 'photo',
    videoQuality: 'high',
    durationLimit: 10,
    maxWidth: 600,
    maxHeight: 600,
    aspectX: 2,
    aspectY: 1,
    angle: 0,

    quality:0.75,
    allowsEditing:true,
    noData:false,
    storageOptions: {
        skipBackup: true,
        path:'images'
    }
};

var currentThis;

export default class User extends BaseComponent {

    // 自定义 反馈回
    static navigationOptions = ({navigation})=>({
       // title: '用户',//navigation 的默认设置属性 标题,  返回 是默认的
        headerLeft:(
            <TouchableWithoutFeedback onPress={()=>{ navigation.state.params.leftPress()}}>
                <View style={{flex:1,flexDirection:'row',justifyContent:'flex-start',alignItems:'center'}}>
                    <Image style={{ width:10 ,height:20,marginLeft:10}} source={ url }/>

                </View>
            </TouchableWithoutFeedback>

        ),
        title:'用户设置'

    })

    //返回前一个页面
    leftPress(){

        var nickName = this.state.nickName;
        var gender = this.state.gender;

        //返回前一个 页面
        let {navigate,goBack,state}=this.props.navigation;
        state.params.callback(nickName,gender);
        goBack();

    }

    constructor(props) {
        super(props);
        currentThis=this;
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            nickName: '',
            gender: '',
            avartUrl: null,

            showIndictor: false,// 加载 提示框
            modalVble: false,// 性别弹出框
            datas: ds.cloneWithRows([{'id': '1', 'text': '男'},
                {'id': '0', 'text': '女'}]),

        };

    }


    componentWillMount() {
        let params = this.props.navigation.state.params;

        if (params) {
            this.setState({
                nickName: params.nickName,
                gender: params.gender,
                avartUrl: params.avartUrl,
            })
        }


    }

    //必须 在navigation  注册 事件名
    componentDidMount(){
        this.props.navigation.setParams({
            leftPress:()=>{
               this.leftPress();
            }
        })


    }

    //更新 信息
    _updateUserInfo() {

        var nickName = this.state.nickName;
        var gender = this.state.gender;

        let params = {};
        params.nickName = nickName;
        params.gender = gender;

        this.setState({showIndictor: true});


        base.network.getUipData(N005_USERS$_EDIT_SYSUSERS, params,
            (successData) => {
                this.setState({showIndictor: false});

                console.log(JSON.stringify(successData));
                base.toastShort('修改成功');


            },
            (error) => {
                this.setState({showIndictor: false})
                base.toastShort('修改失败：' + error);


            });

    }

    //返回的监听？？
    _skip(page) {
        this.props.navigation.navigate('MinePage', {'name': page});
    }

    //展示 性别提示选择框
    _showDialog() {

      return  <View >


            <Modal
                animationType={"fade"}
                transparent={true }
                visible={this.state.modalVble}
                onRequestClose={() => {
                    console.log("abcdefg");
                }}>

                <View style={{flex: 1, justifyContent: 'flex-end', alignItems: 'center',marginBottom:20}}>
                    <View style={{

                        width: '94%',

                        height: 180,

                        flexDirection: 'column',
                        justifyContent: 'flex-end',
                        alignItems: 'center',
                        backgroundColor: '#f5f5dc'
                    }}>

                        <Text style={{marginTop: 10}}>---- 请选择性别 ----</Text>

                        <ListView
                            style={{marginTop: 20}}
                            contentContainerStyle={{}}
                            dataSource={this.state.datas}
                            renderRow={(rowData) => {
                                return <Text style={[{
                                    color: '#212121',
                                    fontSize: 20,
                                }]}
                                  onPress={() => this.genderSelected(rowData.id)} >
                                    {rowData.text}
                                    </Text>
                            }}

                            stickySectionHeadersEnabled={true}
                            showsVertivalScrollIndicator={false}
                        />

                        <Text style={{marginBottom: 20}} onPress={() => {
                            this.setState({modalVble: false})
                        }}>取消</Text>

                    </View>
                </View>

            </Modal>
        </View>
    }

    //选中了某一项
    genderSelected(id) {

        this.setState({
            gender: id,
            modalVble: false,

        });

    }

    //选择图片
    _pickPhoto(){
        //base.toastShort("选择照片");
        ImagePicker.showImagePicker(options,(res) => {

            if (res.didCancel) {  // 返回
                return
            }   else if (res.error) {
                alert("ImagePicker发生错误：" + response.error);
            }
            else if (res.customButton) {
                alert("自定义按钮点击：" + response.customButton);
            }
            else {
                // let source = { uri: res.uri };
                // You can also display the image using data:
                // let source = { uri: 'data:image/jpeg;base64,' + response.data };
               this. _upLoadImage(res.uri);

                this.setState({
                    avartUrl: res.uri
                })
            }
        })
    }

    _upLoadImage(uri){
        //没成功
        // let formData = {"mFile": {uri: uri, type: 'application/octet-stream', name: 'touxiaing.png'}};
        // let formData = {};
        // formData.mFile=uri;
        // base.network.upFileData(N007_USERS$_AVART,formData,succ=>{
        //     alert(JSON.stringify(succ))
        // },error=>{
        //     alert(error)
        // })
    }

    _setHeaderImage(){
        if(this.state.avartUrl){

            return(
                <Image source={{uri:this.state.avartUrl}}
                       style={{width: 100, height: 100, marginRight: 20, marginTop: 10 ,borderRadius:50,borderColor:'#0aafff'}}/>
            )
        }else {
            return(
                <Image source={url_head}
                       style={{width: 100, height: 100, marginRight: 20, marginTop: 10 ,borderRadius:50,borderColor:'#0aafff'}}/>
            )
        }
    }

    render() {

        var gender_text = this.state.gender == "1" ? "男" : "女";
        // var icon = this.state.avartUrl ? {uri: this.state.avartUrl} : url_head;

        return (

            <View style={ styles.container}>


                {/*加载框*/}
                <AppIndictor
                    modalVisible={this.state.showIndictor}
                    size={'large'}
                    color={'#ff6138'}
                />


                <View style={ styles.inputRow1_inner}>


                    <TouchableOpacity style={[styles.marginTop20, styles.marginBottom20]} onPress={this._pickPhoto.bind(this)}>

                        {this._setHeaderImage()}
                    </TouchableOpacity>

                    <View style={[styles.line, {height: 20}]}></View>


                    <View style={[styles.inputRow, {marginTop: 20,backgroundColor:'#f5f5dc'}]}>
                        <Text style={ [styles.label ]}>姓名 : </Text>
                        <TextInput
                            textAlign='left'
                            underlineColorAndroid={'transparent'}
                            keyboardType='default'
                            clearButtonMode='while-editing'
                            style={[styles.input,{}]}
                            placeholder="姓名"
                            placeholderTextColor='#808080'
                            onChangeText={(text) => this.setState({nickName: text})}
                            value={this.state.nickName}/>
                    </View>


                    <View style={[styles.inputRow, { marginTop: 20,backgroundColor:'#f5f5dc',paddingBottom:10,paddingTop:10}]}>

                        <Text style={[styles.label]}>性别 : </Text>

                        <TouchableOpacity onPress={() => {
                            this.setState({modalVble: true});
                        }}>

                            <Text style={[styles.input,{ marginLeft:10}]}>{gender_text}</Text>

                        </TouchableOpacity>


                    </View>


                    <TouchableOpacity style={[styles.btn, styles.marginTop30, {
                        flexDirection: "column",
                        justifyContent: "center",
                        alignItems: "center",
                    }]} onPress={this._updateUserInfo.bind(this)}>
                        <Text style={{color: '#fff', fontSize: 16}}>保存修改</Text>
                    </TouchableOpacity>

                    {this._showDialog()}

                </View>


            </View>
        );


    };


}


const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: "column",
        justifyContent: "flex-start",
        alignItems: "center",

    },


    inputRow1_inner: {
        marginTop: 20,
        backgroundColor: '#fff',
        flexDirection: 'column',
        justifyContent: 'flex-start',
        alignItems: 'center',
        height: "96%",
        width: "94%",
    },
    marginTop20: {
        marginTop: 20
    }, marginTop30: {
        marginTop: 30
    },
    marginBottom20: {
        marginBottom: 20
    },
    line: {
        backgroundColor: '#808080',
        height: 1,
        width: '100%',

    },
    btn: {
        //padding: 10,
        backgroundColor: 'cadetblue',
        height: 50,
        width: '90%',
        justifyContent: 'center',

    },
    text: {

        color: '#fff',
        fontSize: 18,
        marginLeft: 20,


    },
    label: {
        //flex:1,
        width: 80,
        fontSize: 16,
        color: '#212121',
    },
    inputRow: {
        backgroundColor: '#00000000',
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems:'center',
        width: '90%',
        paddingLeft: 20,
        paddingRight: 20,
        marginTop: 5,
    },
    input: {
        height: 40,
        color: '#808080',
        flex: 10,
        width: 150,
        fontSize: 15,
    },

});